﻿using System;
using System.ComponentModel;
using System.Linq;
using Microsoft.WowAddonStudio.FrameXml.Components.TypeConverters;
using Microsoft.WowAddonStudio.FrameXml.Serialization.Attributes;

namespace Microsoft.WowAddonStudio.FrameXml.Components.Descriptors.Filters
{
    public class InheritsListPropertyDescriptorFilter : PropertyDescriptorFilter
    {
        /// <summary>
        /// Filters the specified control.
        /// </summary>
        /// <param name="instance">The instance.</param>
        /// <param name="propertyDescriptor">The property descriptor.</param>
        /// <returns>A property descriptor</returns>
        public override PropertyDescriptor Filter(object instance, PropertyDescriptor propertyDescriptor)
        {
            if (!(instance is IFrameXmlComponent))
                throw new ArgumentException("Only FrameXML components can be filtered.", "instance");

            var component = instance as IFrameXmlComponent;
            var inheritsListAttribute = propertyDescriptor.Attributes.OfType<InheritsListAttribute>().FirstOrDefault();
            if (inheritsListAttribute != null)
            {
                Type genericType = inheritsListAttribute.InheritableObjectType ?? component.SerializationObjectType;
                Type inheritanceTypeConverterType = typeof(InheritanceTypeConverter<,>).MakeGenericType(genericType, propertyDescriptor.PropertyType);
                return TypeDescriptor.CreateProperty(propertyDescriptor.ComponentType, propertyDescriptor, new TypeConverterAttribute(inheritanceTypeConverterType));
            }

            return propertyDescriptor;
        }
    }
}
